package com.mojawa.mj_amap.location

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.model.LatLng
import com.mojawa.mj_amap.MJApplication
import com.mojawa.mj_amap.manager.MJLocationDataManager
import com.mojawa.mj_util.time.MJTimeManager
import com.mojawa.mj_util.time.MJTimeUtil


class MJAMapLocationService : Service(), AMapLocationListener {

    private var mlocationClient: AMapLocationClient? = null
    private var mLocationOption: AMapLocationClientOption? = null
    private val points: MutableList<LatLng> = ArrayList()
    private var MJLocationDataManager: MJLocationDataManager? = null
    private var timerManager = MJTimeManager.getInstance()
    private var second : Long? = null

    override fun onCreate() {
        super.onCreate()
        Log.d("AmapLocationService", "Service created")
        try {
            //升级到34前台服务也需要开启
            MJApplication.initAmap(this)
            //开始定位
            startLocation()
            //开始计时
            startTimer()
            MJLocationDataManager = MJLocationDataManager()

        } catch (e: Exception) {
            Log.e("AmapLocationServiceonCreate", "onCreate: ", e)
            throw RuntimeException(e)
        }
    }

    private fun startTimer() {
        timerManager?.startTimer(object : MJTimeManager.TimerUpdateListener {
            override fun onTimerUpdate(seconds: Long) {
                    second = seconds
            }
        })
    }

    @Throws(Exception::class)
    private fun startLocation() {
        mlocationClient = AMapLocationClient(applicationContext)
        mLocationOption = AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            interval = 1000 // 每1秒更新一次位置
        }
        mlocationClient?.setLocationListener(this)
        mlocationClient?.setLocationOption(mLocationOption)
        mlocationClient?.startLocation()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("AmapLocationService", "Service started")
        // 开启前台服务，避免被系统杀掉
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    "LOCATION_CHANNEL",
                    "Location Service Channel",
                    NotificationManager.IMPORTANCE_LOW
                )
                val manager = getSystemService(NotificationManager::class.java)
                manager?.createNotificationChannel(channel)
            }

            val notification: Notification = NotificationCompat.Builder(this, "LOCATION_CHANNEL")
                .build()
            startForeground(1, notification)

            return START_STICKY
        } catch (e: Exception) {
            Log.e("AmapLocationServiceonStartCommand", "onStartCommand: ", e)
            throw RuntimeException(e)
        }
    }

    override fun onLocationChanged(aMapLocation: AMapLocation?) {
        try {
            if (MJTimeUtil.isPaused) return

            if (aMapLocation != null && aMapLocation.errorCode == 0) {
                val newLatLng = LatLng(aMapLocation.latitude, aMapLocation.longitude)

                // 恢复后的第一个位置更新不计算距离
                if (MJTimeUtil.isFirstLocationAfterResume) {
                    Log.d("MJAMapLocationService", "First location update after resume, not calculating distance")
                    points.clear() // 清空之前的点
                    points.add(newLatLng)
                    MJTimeUtil.isFirstLocationAfterResume = false
                    return
                }

                // 检查上一个点，避免相同的点重复记录
                val lastPoint = points.lastOrNull()
                if (lastPoint == null || newLatLng != lastPoint) {
                    points.add(newLatLng)
                    MJLocationDataManager?.addPoint(listOf(newLatLng))  // 只传递新增的点

                    // 发送广播通知更新距离
                    sendDistanceBroadcast(MJLocationDataManager?.totalDistance, MJLocationDataManager?.getPoints())
                } else {
                    Log.d("MJAMapLocationService", "Same location, skipping distance calculation")
                }
            }
        } catch (e: Exception) {
            Log.e("AmapLocationServiceonLocationChanged", "onLocationChanged: ", e)
            throw RuntimeException(e)
        }
    }

    private fun sendDistanceBroadcast(totalDistance: Double?, points: List<LatLng>?) {
        Log.i("AmapLocationSer", "sendDistanceBroadcast: 发送了")
        val intent = Intent("RunMiddleDistance")
        intent.putExtra("total_distance", totalDistance)
        // 将 List<LatLng> 转换为 ArrayList<LatLng>
        val pointsArrayList = ArrayList(points)
        intent.putParcelableArrayListExtra("points", pointsArrayList)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }
    private fun saveLocationData(points: List<LatLng>, distance: Double) {
        // 保存points和distance到SharedPreferences、数据库或其他存储
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            mlocationClient?.stopLocation()
            mlocationClient?.onDestroy()
        } catch (e: Exception) {
            Log.e("AmapLocationServiceonDestroy", "onDestroy: e", e)
            throw RuntimeException(e)
        }
    }
}